using System;
using System.Net;
using System.Net.Http;
using System.IO;
using System.Text;
using System.Windows.Forms;
using CCWin;
using Newtonsoft.Json;

namespace Mes.质检管理.MaterialChenck
{
    public partial class CheckDetial : Skin_DevExpress
    {
        public string InspectionNo { get; set; }
        public int InspectionId { get; set; }
        public string Supplier { get; set; }
        public string InspectionDate { get; set; }

        private const string API_BASE = "/api/Inspection";

        public CheckDetial()
        {
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            lblInspectionNoVal.Text = InspectionNo ?? string.Empty;
            lblSupplierVal.Text = Supplier ?? string.Empty;
            lblDateVal.Text = InspectionDate ?? string.Empty;

            // 根据 InspectionId 先获取完整的质检基础信息，再查询关联数据
            if (InspectionId > 0)
            {
                TryFillBasicInfo();
            }
            else
            {
                MessageBox.Show("InspectionId为0，无法查询数据", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void TryFillBasicInfo()
        {
            try
            {
                // 直接根据质检表ID获取原料信息和质检明细
                TryFillMaterialByInspectionId();
                TryFillDetailByInspectionId();
            }
            catch (Exception ex)
            {
                // 静默处理错误，不弹窗
                Console.WriteLine($"获取质检信息失败：{ex.Message}");
            }
        }

        private void TryFillMaterialByInspectionId()
        {
            try
            {
                // 直接根据质检表ID获取原料信息
                string url = HttpClientHelper.GetApiUrl("/api/Inspection/GetMaterialByInspectionId") + $"?InspectionId={InspectionId}";
                var json = HttpGet(url);
                var resp = JsonConvert.DeserializeObject<ApiResult<MateriaMessageModel>>(json);
                if (resp != null && resp.code == 200 && resp.data != null)
                {
                    lblMaterialNoVal.Text = resp.data.MaterialNo;
                    lblMaterialNameVal.Text = resp.data.MaterialName;
                    lblMaterialCategoryVal.Text = resp.data.MaterialCategory;
                    lblMaterialSizeVal.Text = resp.data.MaterialSize;
                    lblBatchTotalQuantityVal.Text = resp.data.BatchTotalQuantity.ToString();
                }
            }
            catch (Exception ex)
            {
                // 静默处理错误，不弹窗
                Console.WriteLine($"获取物料信息失败：{ex.Message}");
            }
        }

        private void TryFillDetailByInspectionId()
        {
            try
            {
                // 直接根据质检表ID获取质检明细
                string url = HttpClientHelper.GetApiUrl("/api/Inspection/GetDetailByInspectionId") + $"?InspectionId={InspectionId}";
                var json = HttpGet(url);
                var resp = JsonConvert.DeserializeObject<ApiResult<InspectionDetailModel>>(json);
                if (resp != null && resp.code == 200 && resp.data != null)
                {
                    lblInspectionQuantityVal.Text = resp.data.InspectionQuantity.ToString();
                    lblQualifiedQuantityVal.Text = resp.data.QualifiedQuantity.ToString();
                    lblUnqualifiedQuantityVal.Text = resp.data.UnqualifiedQuantity.ToString();
                    lblInspectorVal.Text = resp.data.Inspector;
                    lblRemarksVal.Text = resp.data.Remarks;
                    lblInspectionResultVal.Text = resp.data.InspectionResult;
                }
            }
            catch (Exception ex)
            {
                // 静默处理错误，不弹窗
                Console.WriteLine($"获取质检明细失败：{ex.Message}");
            }
        }

        private void TryFillMaterial(int materialInfoId)
        {
            if (materialInfoId <= 0) return;
            
            try
            {
                // 使用 MaterialInfoId 查询原料信息
                string url = HttpClientHelper.GetApiUrl("/api/Inspection/GetMaterialById") + $"?Id={materialInfoId}";
                var json = HttpGet(url);
                var resp = JsonConvert.DeserializeObject<ApiResult<MateriaMessageModel>>(json);
                if (resp != null && resp.code == 200 && resp.data != null)
                {
                    lblMaterialNoVal.Text = resp.data.MaterialNo;
                    lblMaterialNameVal.Text = resp.data.MaterialName;
                    lblMaterialCategoryVal.Text = resp.data.MaterialCategory;
                    lblMaterialSizeVal.Text = resp.data.MaterialSize;
                    lblBatchTotalQuantityVal.Text = resp.data.BatchTotalQuantity.ToString();
                }
            }
            catch (Exception ex)
            {
                // 静默处理错误，不弹窗
                Console.WriteLine($"获取物料信息失败：{ex.Message}");
            }
        }

        private void TryFillDetail(int inspectionDetailId)
        {
            if (inspectionDetailId <= 0) return;
            
            try
            {
                // 使用 InspectionDetailId 查询质检明细
                string url = HttpClientHelper.GetApiUrl("/api/Inspection/GetDetailById") + $"?Id={inspectionDetailId}";
                var json = HttpGet(url);
                var resp = JsonConvert.DeserializeObject<ApiResult<InspectionDetailModel>>(json);
                if (resp != null && resp.code == 200 && resp.data != null)
                {
                    lblInspectionQuantityVal.Text = resp.data.InspectionQuantity.ToString();
                    lblQualifiedQuantityVal.Text = resp.data.QualifiedQuantity.ToString();
                    lblUnqualifiedQuantityVal.Text = resp.data.UnqualifiedQuantity.ToString();
                    lblInspectorVal.Text = resp.data.Inspector;
                    lblRemarksVal.Text = resp.data.Remarks;
                    lblInspectionResultVal.Text = resp.data.InspectionResult;
                }
            }
            catch (Exception ex)
            {
                // 静默处理错误，不弹窗
                Console.WriteLine($"获取质检明细失败：{ex.Message}");
            }
        }

        private string HttpGet(string url)
        {
            try
            {
                // 使用HttpClient直接调用接口
                using (var httpClient = new HttpClient())
                {
                    // 设置超时时间
                    httpClient.Timeout = TimeSpan.FromSeconds(30);
                    
                    // 发送GET请求
                    var response = httpClient.GetAsync(url).Result;
                    
                    // 检查响应状态
                    if (response.IsSuccessStatusCode)
                    {
                        // 读取响应内容
                        return response.Content.ReadAsStringAsync().Result;
                    }
                    else
                    {
                        // 处理错误响应
                        string errorContent = response.Content.ReadAsStringAsync().Result;
                        Console.WriteLine($"API调用失败: {response.StatusCode} - {errorContent}");
                        return null;
                    }
                }
            }
            catch (Exception ex)
            {
                // 处理异常
                Console.WriteLine($"调用接口时发生错误: {ex.Message}");
                return null;
            }
        }
    }

    // 复用同命名空间内已定义的 ApiResult<T>

    public class MateriaMessageModel
    {
        public string MaterialNo { get; set; }
        public string MaterialName { get; set; }
        public string MaterialCategory { get; set; }
        public string MaterialSize { get; set; }
        public int BatchTotalQuantity { get; set; }
    }

    public class InspectionDetailModel
    {
        public int InspectionQuantity { get; set; }
        public int QualifiedQuantity { get; set; }
        public int UnqualifiedQuantity { get; set; }
        public string Inspector { get; set; }
        public string Remarks { get; set; }
        public string InspectionResult { get; set; }
    }

    public class InspectorBasicModel
    {
        public int Id { get; set; }
        public string InspectionNo { get; set; }
        public string InspectionName { get; set; }
        public DateTime InspectionDate { get; set; }
        public string Inspector { get; set; }
        public string Supplier { get; set; }
        public int MaterialInfoId { get; set; }
        public int ProductId { get; set; }
        public int InventoryInfoId { get; set; }
        public int InspectionDetailId { get; set; }
    }
}

